package classmate.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import classmate.po.Room;
import classmate.service.ClassmateService;
import classmate.view.StudentFrame;
import classmate.view.RoomDialog;

public class RoomController implements ActionListener {
	private StudentFrame classmateFrame;
	private ClassmateService classmateService;
	private RoomDialog roomDialog;

	public RoomController() {
		super();
		classmateService = new ClassmateService();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		// 打开新增宿舍面板
		if ("addRoomDialog".equals(e.getActionCommand())) {
			roomDialog = new RoomDialog(classmateFrame, "添加宿舍", null);
		}
		// 新增提交
		else if ("addRoom".equals(e.getActionCommand())) {
			Room newRoom = this.getRoomInstance();
			if (newRoom != null) {
				classmateService.addRoom(newRoom);
				JOptionPane.showMessageDialog(classmateFrame, "添加" + newRoom.getRoomNo() + "宿舍成功！");
				roomDialog.dispose();
			} else {
				JOptionPane.showMessageDialog(classmateFrame, "添加宿舍失败");
			}
		}

	}

	public Room getRoomInstance() {
		int roomNo = 0;
		String roomName = null;
		Room room = null;
		String roomNoInput = roomDialog.getRoomNoTextField().getText().trim();
		if (roomNoInput != null && !"".equals(roomNoInput)) {
			if (roomNoInput.matches("^[0-9]*$")) {
				roomNo = Integer.parseInt(roomNoInput);
			} else {
				JOptionPane.showMessageDialog(classmateFrame, "宿舍号必须是整数类型", "输入错误", JOptionPane.ERROR_MESSAGE);
			}
		} else {
			JOptionPane.showMessageDialog(classmateFrame, "宿舍号不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		String roomNameInput = roomDialog.getRoomNameTextField().getText().trim();
		if (roomNameInput != null && !"".equals(roomNameInput)) {
			roomName = roomNameInput;
		} else {
			JOptionPane.showMessageDialog(classmateFrame, "宿舍名不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		if (roomNo > 0 && roomName != null) {
			room = new Room(roomNo, roomName);
		}
		return room;

	}

	public void setRoomDialog(RoomDialog roomDialog) {
		this.roomDialog = roomDialog;
	}

	public void setClassmateFrame(StudentFrame classmateFrame) {
		this.classmateFrame = classmateFrame;
	}

	public ClassmateService getClassmateService() {
		return classmateService;
	}

}
